package com.heima.admin.aspect;


import com.heima.admin.service.IAdUserLoginService;
import com.heima.admin.service.OperateLogService;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.base.annotation.Log;
import com.heima.model.base.po.OperateLog;
import com.heima.utils.common.UserIdThreadLocal;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author 17250
 */
@Aspect
@Component
@RequiredArgsConstructor
public class LogsAspect {

    private final HttpServletRequest request;

    private final OperateLogService operateLogService;

    private final IAdUserLoginService adUserLoginService;

    private static final Logger log = LoggerFactory.getLogger(Log.class);

    /**
     * 生成执行记录 并写入operateLog数据库
     */
    @AfterReturning(pointcut = "@annotation(log)")
    public Object logAround(JoinPoint joinPoint, Log log) throws Throwable {
        OperateLog operateLog = new OperateLog();

        operateLog.setOperTime(LocalDateTime.now());

        // 设置方法名称
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        operateLog.setOperUrl(className + "." + methodName + "()");

        // 设置请求方式
        operateLog.setRequestMethod(request.getMethod());
        // 处理设置注解上的参数
        operateLog.setTitle(log.title());
        operateLog.setTitle("leadnews-admin");
        operateLog.setBusinessType(log.businessType().ordinal());
        operateLog.setOperatorType(log.operatorType().ordinal());

        //获取操作者Id
        Integer userId = UserIdThreadLocal.getUserId();
        AdUser user = adUserLoginService.getById(userId);
        operateLog.setOperName(user.getName());

        operateLog.setCreateTime(LocalDateTime.now());
        operateLogService.save(operateLog);

        return null;
    }
}
